home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / SQLTEST.PY < prev    next >
Encoding:
Python Source  |  2000-05-30  |  9.4 KB  |  235 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. '''Inserting optional tests with 'sqlgroup'
  65.   
  66.     It is sometimes useful to make inputs to an SQL statement
  67.     optinal.  Doing so can be difficult, because not only must the
  68.     test be inserted conditionally, but SQL boolean operators may or
  69.     may not need to be inserted depending on whether other, possibly
  70.     optional, comparisons have been done.  The 'sqlgroup' tag
  71.     automates the conditional insertion of boolean operators.  
  72.  
  73.     The 'sqlgroup' tag is a block tag that has no attributes. It can
  74.     have any number of 'and' and 'or' continuation tags.
  75.  
  76.     Suppose we want to find all people with a given first or nick name
  77.     and optionally constrain the search by city and minimum and
  78.     maximum age.  Suppose we want all inputs to be optional.  We can
  79.     use DTML source like the following::
  80.  
  81.       <dtml-sqlgroup>
  82.         <dtml-sqlgroup>
  83.           <dtml-sqltest name column=nick_name type=nb multiple optional>
  84.         <dtml-or>
  85.           <dtml-sqltest name column=first_name type=nb multiple optional>
  86.         </dtml-sqlgroup>
  87.       <dtml-and>
  88.         <dtml-sqltest home_town type=nb optional>
  89.       <dtml-and>
  90.         <dtml-if minimum_age>
  91.            age >= <dtml-sqlvar minimum_age type=int>
  92.         </dtml-if>
  93.       <dtml-and>
  94.         <dtml-if maximum_age>
  95.            age <= <dtml-sqlvar maximum_age type=int>
  96.         </dtml-if>
  97.       </dtml-sqlgroup>
  98.  
  99.     This example illustrates how groups can be nested to control
  100.     boolean evaluation order.  It also illustrates that the grouping
  101.     facility can also be used with other DTML tags like 'if' tags.
  102.  
  103.     The 'sqlgroup' tag checks to see if text to be inserted contains
  104.     other than whitespace characters.  If it does, then it is inserted
  105.     with the appropriate boolean operator, as indicated by use of an
  106.     'and' or 'or' tag, otherwise, no text is inserted.
  107.  
  108. '''
  109. __rcs_id__='$Id: sqltest.py,v 1.13 2000/05/30 15:46:55 brian Exp $'
  110.  
  111. ############################################################################
  112. #     Copyright 
  113. #
  114. #       Copyright 1996 Digital Creations, L.C., 910 Princess Anne
  115. #       Street, Suite 300, Fredericksburg, Virginia 22401 U.S.A. All
  116. #       rights reserved.
  117. #
  118. ############################################################################ 
  119. __version__='$Revision: 1.13 $'[11:-2]
  120.  
  121. import sys
  122. from DocumentTemplate.DT_Util import ParseError, parse_params, name_param
  123. str=__builtins__['str']
  124.  
  125. from string import find, split, join, atoi, atof
  126. from types import ListType, TupleType, StringType
  127.  
  128. class SQLTest: 
  129.     name='sqltest'
  130.     optional=multiple=None
  131.  
  132.     def __init__(self, args):
  133.         args = parse_params(args, name='', type=None, column=None,
  134.                             multiple=1, optional=1, op=None)
  135.         self.__name__ = name_param(args,'sqlvar')
  136.         has_key=args.has_key
  137.         if not has_key('type'):
  138.             raise ParseError, ('the type attribute is required', 'sqltest')
  139.         self.type=t=args['type']
  140.         if not valid_type(t):
  141.             raise ParseError, ('invalid type, %s' % t, 'sqltest')
  142.         if has_key('optional'): self.optional=args['optional']
  143.         if has_key('multiple'): self.multiple=args['multiple']
  144.         if has_key('column'): self.column=args['column']
  145.         else: self.column=self.__name__
  146.  
  147.         # Deal with optional operator specification
  148.         op = '='                        # Default
  149.         if has_key('op'):
  150.             op = args['op']
  151.             # Try to get it from the chart, otherwise use the one provided
  152.             op = comparison_operators.get(op, op)
  153.         self.op = op
  154.  
  155.     def render(self, md):
  156.         name=self.__name__
  157.         t=self.type
  158.         try: v = md[name]
  159.         except KeyError, key:
  160.             if str(key)==name and self.optional: return ''
  161.             raise KeyError, key, sys.exc_info()[2]
  162.             
  163.         
  164.         if type(v) in (ListType, TupleType):
  165.             if len(v) > 1 and not self.multiple:
  166.                 raise 'Multiple Values', (
  167.                     'multiple values are not allowed for <em>%s</em>'
  168.                     % name)
  169.         else: v=[v]
  170.         
  171.         vs=[]
  172.         for v in v:
  173.             if not v and type(v) is StringType and t != 'string': continue
  174.             if t=='int':
  175.                 try:
  176.                     if type(v) is StringType: atoi(v)
  177.                     else: v=str(int(v))
  178.                 except:
  179.                     raise ValueError, (
  180.                         'Invalid integer value for <em>%s</em>' % name)
  181.             elif t=='float':
  182.                 if not v and type(v) is StringType: continue
  183.                 try:
  184.                     if type(v) is StringType: atof(v)
  185.                     else: v=str(float(v))
  186.                 except:
  187.                     raise ValueError, (
  188.                         'Invalid floating-point value for <em>%s</em>' % name)
  189.             else:
  190.                 v=str(v)
  191.                 v=md.getitem('sql_quote__',0)(v)
  192.                 #if find(v,"\'") >= 0: v=join(split(v,"\'"),"''")
  193.                 #v="'%s'" % v
  194.     
  195.             vs.append(v)
  196.  
  197.         if not vs:
  198.             if self.optional: return ''
  199.             raise 'Missing Input', (
  200.                 'No input was provided for <em>%s</em>' % name)
  201.  
  202.         if len(vs) > 1:
  203.             vs=join(map(str,vs),', ')
  204.             return "%s in (%s)" % (self.column,vs)
  205.         return "%s %s %s" % (self.column, self.op, vs[0])
  206.  
  207.     __call__=render
  208.  
  209. valid_type={'int':1, 'float':1, 'string':1, 'nb': 1}.has_key
  210.  
  211. comparison_operators = { 'eq': '=', 'ne': '<>',
  212.                          'lt': '<', 'le': '<=', 'lte': '<=',
  213.                          'gt': '>', 'ge': '>=', 'gte': '>=' }
  214.